import moment from 'moment';
import React, { useEffect } from 'react';
import { useTablePipeline } from 'ali-react-table';
import InfiniteScroll from 'react-infinite-scroller';
import { Drawer, Spin, message, Timeline } from 'antd';

import { HttpCode } from '#/utils/contacts.js';
import { useTRState } from '#/utils/trHooks.jsx';
import { DownSquareOutlined, UpSquareOutlined } from '#/utils/antdIcons';

import planIcon from '@/assets/img/plan_icon.png';
import { TRDefault } from '@/components/index.js';
import { TjTable } from '@/pages/ETrade/components/index.js';

import { queryProvincialSpotBiddingLog } from '../../../service';
import { columns } from '../../../dictionary';
import styles from './index.less';

const OutputPlanOperationLog = (props) => {
  const { visible = false, formValue, onClose } = props;

  const [state, setState] = useTRState({
    data: [],
    loading: false,
    error: false,
    isLoading: false,
    hasMore: true,
    currentData: [],
  });
  const { data, loading, error, isLoading, hasMore, currentData } = state;

  // 初始化数据
  const fetchData = async (val) => {
    const { calendarDate, stationId } = val;
    const params = { reportDate: calendarDate, stationId };
    setState({
      loading: true,
      error: false,
    });
    const res = await queryProvincialSpotBiddingLog(params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _data = (res?.data || []).map((item, index) => ({
        ...item,
        id: index + 1,
      }));
      setState({
        data: _data,
        currentData: _data.length > 20 ? _data?.splice(0, 20) : _data,
      });
    } else {
      setState({
        error: true,
      });
      message.info(res?.message || '系统异常');
    }
    setState({
      loading: false,
    });
  };

  // 取消
  const _onCancel = () => {
    onClose && onClose();
  };

  const loadMore = (currentPage) => {
    if (!hasMore) return;
    setState({
      isLoading: true,
      hasMore: data.length > 20 * currentPage ? true : false,
    });

    const _data = [...data].splice(currentPage * 20, 20);
    setTimeout(() => {
      setState({
        isLoading: false,
      });
    }, 1000);
    setState({
      currentData: [...currentData, ..._data],
    });
  };

  const onSpread = (record) => {
    let _data = [...data];
    let _currentData = [...currentData];
    _data = _data.map((item) => {
      return {
        ...item,
        isSpread: item.id === record.id ? !item.isSpread : item?.isSpread,
      };
    });
    _currentData = _currentData.map((item) => {
      return {
        ...item,
        isSpread: item.id === record.id ? !item.isSpread : item?.isSpread,
      };
    });
    setState({
      data: _data,
      currentData: _currentData,
    });
  };

  useEffect(() => {
    if (formValue?.calendarDate && formValue?.stationId && visible) {
      fetchData(formValue);
    }
  }, [visible]);

  return (
    <Drawer
      width={680}
      className={styles.operateLogModal}
      visible={visible}
      onClose={_onCancel}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>操作日志</span>
        </div>
      }
      footer={null}
    >
      <div className={styles.container}>
        {loading ? (
          <Spin spinning={loading} />
        ) : error ? (
          <TRDefault type={'emptysm'} message={'系统异常'} />
        ) : data.length ? (
          <Spin spinning={isLoading} className={styles.spinloading}>
            <div className={styles.content}>
              <InfiniteScroll
                initialLoad={false}
                pageStart={0}
                loadMore={loadMore}
                hasMore={!loading && hasMore}
                useWindow={false}
                className={styles.infiniteScroll}
              >
                <Timeline>
                  {currentData.map((item, index) => {
                    return (
                      <Timeline.Item key={index}>
                        <div className={styles.timelineItem}>
                          <div className={styles.header}>
                            <div className={styles.title}>
                              <div className={styles.date}>
                                {moment(item.reportDate).format('YYYY.MM.DD')}
                              </div>
                              <div className={styles.dataFrom}>{item.dataFrom ?? ''}</div>
                              <div className={item.dataFrom == '缺省' ? '' : styles.dataFrom}>
                                {item.startDate ?? ''}
                              </div>
                              <div className={item.dataFrom == '缺省' ? '' : styles.dataFrom}>
                                {item.endDate ?? ''}
                              </div>
                              <div className={styles.type}>{item.status}</div>
                              <div className={styles.spread} onClick={() => onSpread(item)}>
                                {item?.isSpread ? (
                                  <UpSquareOutlined className={styles.spreadLogo} />
                                ) : (
                                  <DownSquareOutlined className={styles.spreadLogo} />
                                )}
                              </div>
                            </div>
                            <div className={styles.updateUser}>
                              <span>操作人：</span>
                              <span className={styles.operationUser}>{item.operationUserName}</span>
                            </div>
                          </div>
                          {item.isSpread && (
                            <div className={styles.bottom}>
                              <div className={styles.antdBaseTable}>
                                <TjTable
                                  style={{ flex: 1, overflowY: 'scroll', marginTop: 15 }}
                                  useVirtual="auto"
                                  defaultColumnWidth={90}
                                  dataSource={item.planList}
                                  columns={columns.filter((t) => t.code !== 'operation')}
                                />
                              </div>
                            </div>
                          )}
                        </div>
                      </Timeline.Item>
                    );
                  })}
                </Timeline>
                {/* {!hasMore && data.length !== 0 && (
                  <div className={styles.loader} key={0}>
                    已经到底了～
                  </div>
                )} */}
              </InfiniteScroll>
            </div>
          </Spin>
        ) : (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        )}
      </div>
    </Drawer>
  );
};

export default OutputPlanOperationLog;
